import os
import subprocess
import re


def get_usb_devices():  # 获取串口设备的标识符
    pattern = r"COM[0-9]+.\s{2,}(\S+VID_.*PID_\S+)\s{2,}\S+\s+\n\n"
    command = "wmic path win32_pnpentity where \"PNPDeviceID like '%%VID_%%'\" get name, PNPDeviceID, status"
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    match = re.findall(pattern, result.stdout)
    if match:
        return match
    else:
        return []


def restart_com_driver():
    pids = get_usb_devices()
    for pid in pids:  # 禁用串口驱动
        os.system(f'''pnputil /disable-device \"{pid}\"''')
    for pid in pids:  # 打开串口驱动
        os.system(f'''pnputil /enable-device \"{pid}\"''')


if __name__ == '__main__':
    restart_com_driver()
